import { GameEngine } from './core/GameEngine.js';
import { GameConfig } from './config/GameConfig.js';

// 游戏主入口
class GameLauncher {
    private gameEngine: GameEngine | null = null;

    async init(): Promise<void> {
        try {
            console.log('🚀 保卫特拉维夫 - 游戏启动中...');
            
            // 显示加载画面
            this.showLoadingScreen();
            
            // 初始化游戏引擎
            this.gameEngine = new GameEngine();
            await this.gameEngine.init();
            
            // 隐藏加载画面
            this.hideLoadingScreen();
            
            // 启动游戏
            this.gameEngine.start();
            
            console.log('✅ 游戏引擎启动成功');
        } catch (error) {
            console.error('❌ 游戏启动失败:', error);
            this.showError('游戏启动失败，请刷新页面重试');
        }
    }

    private showLoadingScreen(): void {
        const gameContainer = document.getElementById('gameContainer');
        if (!gameContainer) return;

        const loadingScreen = document.createElement('div');
        loadingScreen.className = 'loading-screen';
        loadingScreen.id = 'loadingScreen';
        loadingScreen.innerHTML = `
            <div class="loading-spinner"></div>
            <div class="loading-text">保卫特拉维夫</div>
            <div class="loading-progress">正在加载游戏引擎...</div>
        `;
        gameContainer.appendChild(loadingScreen);
    }

    private hideLoadingScreen(): void {
        const loadingScreen = document.getElementById('loadingScreen');
        if (loadingScreen) {
            loadingScreen.remove();
        }
    }

    private showError(message: string): void {
        const gameContainer = document.getElementById('gameContainer');
        if (!gameContainer) return;

        const errorScreen = document.createElement('div');
        errorScreen.className = 'loading-screen';
        errorScreen.style.background = 'linear-gradient(135deg, #8B0000 0%, #DC143C 100%)';
        errorScreen.innerHTML = `
            <div style="font-size: 48px; margin-bottom: 20px;">⚠️</div>
            <div class="loading-text">启动错误</div>
            <div class="loading-progress">${message}</div>
        `;
        
        // 清空容器并显示错误
        gameContainer.innerHTML = '';
        gameContainer.appendChild(errorScreen);
    }
}

// 等待DOM加载完成后启动游戏
document.addEventListener('DOMContentLoaded', async () => {
    const launcher = new GameLauncher();
    await launcher.init();
});

// 导出给全局使用
(window as any).GameLauncher = GameLauncher;
